package cn.how2go.net.server.protocol;

import cn.how2go.net.server.util.BinaryUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

/**
 * 终端注册应答
 */
public class JT_8100 implements JTMessage {
    private static Logger logger = LoggerFactory.getLogger(JT_8100.class);

    //应答流水号
    private short seriaNo;
    //应答结果，0：成功/确认；1：失败；2：消息有误；3：不支持
    private byte result;

    /**
     * 鉴权码,只有在成功后才有该字段
     */
    private String registerNo;

    public JT_8100() {
    }

    public JT_8100(short seriaNo, byte result, String registerNo) {
        this.seriaNo = seriaNo;
        this.result = result;
        this.registerNo = registerNo;
    }

    @Override
    public byte[] write() {
        ByteBuf directBuf = Unpooled.directBuffer(16);
        try {
            directBuf.writeShort(seriaNo);
            directBuf.writeByte(result);
            if(result==0) {
                directBuf.writeBytes(registerNo.getBytes("UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("<<<<组包失败");
            directBuf.release();
            return null;
        }

        byte[] bytess = new byte[directBuf.readableBytes()];
        directBuf.readBytes(bytess);
        directBuf.release();
        return bytess;
    }

    @Override
    public void read(byte[] bytes) {
        ByteBuf directBuf = Unpooled.directBuffer(16);
        directBuf.writeBytes(bytes);
        try {
            this.seriaNo = directBuf.readShort();
            this.result = directBuf.readByte();
            if(result==0) {
                byte[] licenseNoBytes = new byte[bytes.length - 3];
                directBuf.readBytes(licenseNoBytes);
                this.registerNo = new String(licenseNoBytes, "GBK");
            }
        }catch (Exception e){
            logger.error("<<<<解包失败"+ BinaryUtil.ToHexFormatString(bytes));
            directBuf.release();
        }
        directBuf.release();
    }

    @Override
    public short getBodyLength() {
        short len = 3;

        try {
            if (registerNo!= null) {
                byte[] temp = registerNo.getBytes("GBK");
                len += temp.length;
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("转换时意外错误");
        }

        return len;
    }

    public short getSeriaNo() {
        return seriaNo;
    }

    public void setSeriaNo(short seriaNo) {
        this.seriaNo = seriaNo;
    }

    public byte getResult() {
        return result;
    }

    public void setResult(byte result) {
        this.result = result;
    }

    public String getRegisterNo() {
        return registerNo;
    }

    public void setRegisterNo(String registerNo) {
        this.registerNo = registerNo;
    }
}
